package com.mos.simple.socket;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.json.JsonMapper;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.jni.FileInfo;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Description: <br/>
 * date: 2024/09/03 17:07<br/>
 *
 * @author 小尘哥<br />
 */
@Component
@ServerEndpoint(value = "/mos/websocket/{userId}")
@Slf4j
public class WebSocket {
    public static Map<String, Session> livingSession = new ConcurrentHashMap<>();

    private static Map<String, String> CACHE_MESSAGE = new ConcurrentHashMap<>();

    private SeekableByteChannel byteChannel;

    /**
     * 客户端与服务端连接成功
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {

        livingSession.put(userId, session);

        // 判断是否有离线消息，再进行推送
        String offLineMessage = CACHE_MESSAGE.get(userId);
        if (offLineMessage != null) {
            session.getAsyncRemote().sendText(offLineMessage + " 看到消息时间：" + DateUtil.now());
            // 清空消息，避免下次上线重复推送
            CACHE_MESSAGE.remove(userId);
        }
    }

    /**
     * 客户端与服务端连接关闭
     *
     * @param session
     */
    @OnClose
    public void onClose(Session session, @PathParam("userId") String userId) {
        livingSession.remove(userId);
    }

    /**
     * 客户端与服务端连接异常
     *
     * @param error
     * @param session
     */
    @OnError
    public void onError(Throwable error, Session session) {
        error.printStackTrace();
    }

    /**
     * 客户端向服务端发送消息
     *
     * @param message
     * @throws IOException
     */
    @OnMessage
    public void onMsg(String msg) throws IOException {
        MsgEntity msgEntity = JSONUtil.toBean(msg,MsgEntity.class);
        Session session = livingSession.get(msgEntity.getReceiveUserId());
        String msgFmt  = "%s --来自【%s】的消息，现在时间：%s";
        String formatMsg = String.format(msgFmt,msgEntity.getMsg(),msgEntity.getUserId(), DateUtil.now());
        if (session != null) {
            session.getAsyncRemote().sendText(formatMsg);
        }else{
            // 消息暂存
            CACHE_MESSAGE.put(msgEntity.getReceiveUserId(),formatMsg);
        }

    }

    @OnMessage
    public void onMsg(ByteBuffer fileByteBuffer, Session session) throws IOException {
        log.info("msg from {} and msg type is ByteBuffer ", session.getId());
        session.getBasicRemote().sendBinary(fileByteBuffer);

        // 待实现 断点续传、大文件切片等等
    }

}
